<template>
  <div>
    <div class="limiter">
      <div class="container-table103">
        <div class="wrap-table101">
          <div class="progress_box" style="width:90%;">
            <el-progress
              class="progress_line"
              style="width:90%;"
              v-show="progressShow"
              :text-inside="true"
              :stroke-width="22"
              :color="customColor"
              :percentage="c_percentage"
              status="warning"
            ></el-progress>
          </div>
          <el-upload
            v-show="!progressShow"
            class="upload-demo"
            ref="upload"
            :auto-upload="autoUpload"
            :show-file-list="show_file_list"
            :headers="headers"
            drag
            :action="UploadUrl()"
            :limit="1"
            :on-exceed="handleExceed"
            :on-change="onChange"
            :on-success="handleAvatarSuccess"
            :on-progress="handleAvatarProgress"
            :on-error="handleAvatarError"
          >
            <el-image :src="src"></el-image>
            <el-button>立即上传</el-button>
            <div v-show="isvip == 0" class="el-upload__text">
              点击按钮选择应用的安装包，或直接拖拽文件到此区域（支持.IPA或.APK文件，单个文件最大支持{{
                uploadInfo.singlesize
              }}M）
            </div>
            <div v-show="isvip == 1" class="el-upload__text">
              点击按钮选择应用的安装包，或直接拖拽文件到此区域（支持.IPA文件，单个文件最大支持{{
                uploadInfo.singlesize
              }}M）
            </div>
          </el-upload>
        </div>
      </div>
      <!-- <div style="width: 100%; height: 100%;">
        <ossUpload :policy="getpolicy">
          <div>
            <el-image :src="src"></el-image>
            <el-button>立即上传</el-button>
            <div v-show="isvip == 0" class="el-upload__text">
              点击按钮选择应用的安装包，或直接拖拽文件到此区域（支持.IPA或.APK文件，单个文件最大支持{{
                uploadInfo.singlesize
              }}M）
            </div>
            <div v-show="isvip == 1" class="el-upload__text">
              点击按钮选择应用的安装包，或直接拖拽文件到此区域（支持.IPA文件，单个文件最大支持{{
                uploadInfo.singlesize
              }}M）
            </div>
          </div>
        </ossUpload>
      </div> -->
    </div>
  </div>
</template>

<script>
import JsZip, { files } from "jszip";
// import ossUpload from "../common/OSSUpload";
export default {
  //import引入的组件需要注入到对象中才能使用
  components: {
    // ossUpload
  },
  data() {
    //这里存放数据
    return {
      uploadInfo: {},
      src: "../../../static/上传应用按钮.png",
      headers: {},
      c_percentage: 0, //初始进度0
      progressShow: false, //最开始隐藏进度条
      new_zip: [],
      autoUpload: false,
      show_file_list: false,
      reader_c: "", //当前解压zip实体
      appName: "", //APP名称
      version: "", //版本
      Identifier: "", //包名
      zxlogo: "", //APP图标地址
      sext: "", //后缀地址
      upName: "", //上传地址文件名称
      DownLink: "", //下载地址
      AppSize: 0, //APP包大小
      sjid: 0, //升级ID，0为新上传
      // isvip: 0, //是否为超级签名
      customColor: "#ff7226", //进度条颜色
      isStop: 0,
      // getpolicy:'getpolicy'
    };
  },
  props: ["isvip"],
  //监听属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {},
  //方法集合
  methods: {
    uploadsInfo() {
      var params = new URLSearchParams();
      this.$post(this.API.Application_uploadsInfo, params).then(res => {
        if (res) {
          // console.log(res);
          this.uploadInfo = res.data.result;
          // console.log(this.uploadInfo);
        }
      });
    },
    UploadUrl: function() {
      if (
        this.uploadInfo.fileUploadUrl == undefined ||
        this.uploadInfo.fileUploadUrl == null
      ) {
        return "";
      }

      // return this.uploadInfo.fileUploadUrl_test;
      return this.uploadInfo.fileUploadUrl;
    },
    handleRemove(file, fileList) {
      // console.log(file, fileList);
    },
    handlePreview(file) {
      // console.log(file);
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 1 个文件，本次选择了 ${
          files.length
        } 个文件，共选择了 ${files.length + fileList.length} 个文件`
      );
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    //文件选取时，判断逻辑
    onChange(file, fileList) {
      if (this.isStop == 1) {
        console.log(file.status, new Date());
      }
      // if(this.uploadInfo['rzstatus'] != 1){
      //   this.$message.error("请选实名认证!");
      //   this.$refs.upload.clearFiles();

      //   setTimeout(() => {
      //     this.$router.push({
      //       path: '/realName',
      //       name: 'realName',
      //     });
      //   }, 3000);
      //   return;
      // }
      if (file.status == "success") {
        //这里什么都不做-----------------------------------被坑死的一个地方  || file.status == "ready"
        return;
      }
      if (this.isStop == 1) {
        console.log(file.status, new Date());
      }
      file = file.raw;

      // console.log(file);
      let c_fileName = file.name;
      this.upName = file.name;
      let fileArr = c_fileName.split(".");
      this.sext = fileArr[fileArr.length - 1]; //file.name.substr(file.name.length - 3) === "apk"
      const isLt2M = file.size / 1024 / 1024 < this.uploadInfo.singlesize;

      if (
        parseInt(this.uploadInfo.allowsize) <
        parseInt(file.size / 1024 / 1024) +
          parseInt(this.uploadInfo.uploadedsize)
      ) {
        this.$message.error(
          "上传空间，已超出限定大小:" + this.uploadInfo.allowsize + "M"
        );
        this.$refs.upload.clearFiles();
        return;
      }

      if (this.isvip == 1) {
        if (this.sext != "ipa") {
          this.$message.error("上传文件只能是 ipa 格式!");
          this.$refs.upload.clearFiles();
          return;
        }
      } else {
        if (this.sext != "ipa" && this.sext != "apk") {
          this.$message.error("上传文件只能是 ipa/apk 格式!");
          this.$refs.upload.clearFiles();
          return;
        }
      }

      if (!isLt2M) {
        this.$message.error(
          "上传文件大小不能超过 " + this.uploadInfo.singlesize + "MB!"
        );
        this.$refs.upload.clearFiles();
        return;
      }

      let that = this;
      const AppInfoParser = require("app-info-parser");
      const parser = new AppInfoParser(file); // or xxx.ipa
      parser
        .parse()
        .then(result => {
          if (this.isStop == 1) {
            console.log("app info ----> ", result);
          }

          var icon = "";
          var appName = "";
          var hpackageName = "";
          var hversion = "";
          var MinimumOSVersion = "";
          if (this.sext == "apk") {
            appName = result.application.label[0];
            icon = result.icon;
            hpackageName = result.package;
            hversion = result.versionName;
            MinimumOSVersion = result.compileSdkVersion;
          } else if (this.sext == "ipa") {
            appName = result.CFBundleDisplayName;
            icon = result.icon;
            hpackageName = result.CFBundleIdentifier;
            hversion = result.CFBundleShortVersionString;
            MinimumOSVersion = result.MinimumOSVersion;
          }

          // console.log(appName);
          that.appName = appName;
          that.zxlogo = icon;
          that.Identifier = hpackageName;
          that.version = hversion;
          //显示进度条
          that.progressShow = true;
          that.$refs.upload.submit();
        })
        .catch(err => {
          console.log("err ----> ", err);
          this.$message.error(err);
        });
    },

    submitData() {
      var params = new URLSearchParams();
      params.append("DownLink", this.DownLink);
      params.append("hext", this.sext);
      params.append("zxlogo", this.zxlogo);
      params.append("happName", this.appName);
      params.append("iAppSize", this.AppSize);
      params.append("hpackageName", this.Identifier);
      params.append("hversion", this.version);
      params.append("isvip", this.isvip);
      params.append("sjid", this.sjid);
      params.append("apkName", this.upName);
      // console.log(params);
      if (this.isStop == 1) {
        console.log(params, "开始提交数据:" + new Date());
      }
      this.$post(this.API.Appupload_uploadData, params).then(res => {
        if (res) {
          // console.log(res);
          if (this.isStop == 1) {
            console.log(res, "提交数据成功:" + new Date());
          }
          sessionStorage.setItem("setMenuIndex_application", 1);
          sessionStorage.setItem("setMenuIndex_supuer", 1);
          if (this.isStop == 1) {
            console.log("跳转成功:" + new Date());
            return;
          }
          location.reload();
        }
      });
    },
    handleAvatarSuccess(res, file) {
      this.DownLink = res.path;
      this.AppSize = file.size;
      if (this.isStop == 1) {
        console.log("------------开始上传文件:完成", new Date());
      }
      this.submitData();
      // this.imageUrl = URL.createObjectURL(file.raw);
    },
    handleAvatarProgress(res, file) {
      if (this.isStop == 1) {
        console.log("------------开始上传文件:" + res.percent);
      }
      this.c_percentage = parseInt(res.percent);
      // c_percentage
      // this.imageUrl = URL.createObjectURL(file.raw);
    },
    handleAvatarError(res, file) {
      if (this.isStop == 1) {
        console.log(console.log(res), "上传失败：");
      }
      // this.imageUrl = URL.createObjectURL(file.raw);
    }
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {
    var Authorization = sessionStorage["token"];
    this.headers = { Authorization: Authorization };

    var appID = this.$route.query.appID; //appID
    if (appID > 0) {
      this.sjid = appID;
    }

    this.uploadsInfo();

    this.isStop = this.$route.query.isStop;
    // console.log('appID:'+this.sjid);
    // console.log('isvip:'+this.isvip);
  },
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {}
};
</script>
<style scoped>
.progress_box {
  display: flex;
  justify-content: center;
  align-items: center;
}
div >>> .el-button--default {
  border: none;
}
.content {
  margin: 30px 0px 30px 0px;
  background: #ffffff;
  box-shadow: 0px 4px 10px 2px rgba(0, 0, 0, 0.08);
  border-radius: 4px;
}

.limiter {
  width: 100%;
  margin: 0 auto;
}

.container-table103 {
  width: 100%;
  min-height: 100vh;
  display: -webkit-box;
  display: -webkit-flex;
  display: -moz-box;
  display: -ms-flexbox;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-wrap: wrap;
}

.container-table102 {
  width: 100%;
  min-height: 100vh;
  border-radius: 4px 0px 0px 4px;
}

.wrap-table101 {
  width: 1170px;
  display: flex;
  justify-content: center;
  align-items: center;
}

div >>> .el-upload__input {
  display: none;
}

div >>> .el-upload-dragger {
  border: none;
}

.el-button {
  width: 180px;
  /* height: 50px; */
  background-color: #ff7226;
  font-size: 16px;
  color: #fff;
  border-radius: 8px;
}

div >>> .el-button span {
  margin-left: 40px;
}

.el-image {
  position: absolute;
  margin-top: 12px;
  margin-left: 45px;
}

.el-upload__text {
  color: #adadad;
  font-size: 12px;
  /* width: 204px; */
  /* margin-left: 80px; */
  margin-top: 10px;
}

div >>> .el-upload-dragger {
  width: 180px;
  /* height: 50px; */
}

div >>> .upload-demo {
  width: 180px;
  /* height: 50px; */
  position: absolute;
  top: 40%;
}

/* 媒体查询 */
@media (max-width: 992px) {
  .container-table103 {
    min-height: 70vh;
  }
}

@media (max-width: 576px) {
}
</style>
